﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using Newtonsoft.Json.Linq;

namespace ComTools
{
    public partial class frmSocketServer : Form
    {
        public frmSocketServer()
        {
            InitializeComponent();
        }
        //定义回调:解决跨线程访问问题
        private delegate void SetTextValueCallBack(string strValue);
        //定义接收客户端发送消息的回调
        private delegate void ReceiveMsgCallBack(string strReceive);
        //声明
        private ReceiveMsgCallBack receiveCallBack;
        //定义回调：给ComboBox控件添加元素
        private delegate void SetCmbCallBack(string strItem);
        //声明
        private SetCmbCallBack setCmbCallBack;
        //定义发送文件的回调
        private delegate void SendFileCallBack(byte[] bf);
        //声明
        private SendFileCallBack sendCallBack;

        //用于通信的Socket
        Socket socketSend;
        //用于监听的SOCKET
        Socket socketWatch;

        //将远程连接的客户端的IP地址和Socket存入集合中
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();

        //创建监听连接的线程
        Thread AcceptSocketThread;
        //接收客户端发送消息的线程
        Thread threadReceive;

        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Start_Click(object sender, EventArgs e)
        {
            try
            {
                //当点击开始监听的时候 在服务器端创建一个负责监听IP地址和端口号的Socket
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //获取ip地址
                IPAddress ip = null;
                if (this.txt_IP.Text.Trim() == "0.0.0.0")
                {
                    ip = IPAddress.Any;
                }
                else
                {
                    ip = IPAddress.Parse(this.txt_IP.Text.Trim());
                }
                //创建端口号
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txt_Port.Text.Trim()));
                //绑定IP地址和端口号
                socketWatch.Bind(point);
                ShowLog("监听成功");
                //开始监听:设置最大可以同时连接多少个请求
                socketWatch.Listen(10);

                //实例化回调
                receiveCallBack = new ReceiveMsgCallBack(ReceiveMsg);
                setCmbCallBack = new SetCmbCallBack(AddCmbItem);
                sendCallBack = new SendFileCallBack(SendFile);

                //创建线程开始监听
                AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
                AcceptSocketThread.IsBackground = true;
                AcceptSocketThread.Start(socketWatch);
            }
            catch (Exception exc)
            {
                ShowLog(exc.Message);
            }
        }

        private void InneterAccepct(IAsyncResult iasync)
        {
            try
            {
                Socket temp = iasync.AsyncState as Socket;
                //等待客户端的连接，并且创建一个用于通信的Socket
                socketSend = temp.EndAccept(iasync);
                temp.BeginAccept(new AsyncCallback(InneterAccepct), temp);
                //获取远程主机的ip地址和端口号
                string strIp = socketSend.RemoteEndPoint.ToString();
                dicSocket.Add(strIp, socketSend);
                this.cmb_Socket.Invoke(setCmbCallBack, strIp);
                string strMsg = "远程主机：" + socketSend.RemoteEndPoint + "连接成功";
                //使用回调
                ShowLog(strMsg);

                //定义接收客户端消息的线程
                Thread threadReceive = new Thread(new ParameterizedThreadStart(Receive));
                threadReceive.IsBackground = true;
                threadReceive.Start(socketSend);
            }
            catch (Exception exc)
            {
                ShowLog(exc.Message);
            }
        }

        private byte[] inOptionsValue()
        {
            uint dummy = 0;

            byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
            BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
            BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
            BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
            return inOptionValues;
        }

        /// <summary>
        /// 等待客户端的连接，并且创建与之通信用的Socket
        /// </summary>
        /// <param name="obj"></param>
        private void StartListen(object obj)
        {
            Socket socketWatch = obj as Socket;
            socketWatch.BeginAccept(new AsyncCallback(InneterAccepct), socketWatch);
            /*while (true)
            {
                //等待客户端的连接，并且创建一个用于通信的Socket
                socketSend = socketWatch.Accept();
                //获取远程主机的ip地址和端口号
                string strIp = socketSend.RemoteEndPoint.ToString();
                dicSocket.Add(strIp, socketSend);
                this.cmb_Socket.Invoke(setCmbCallBack, strIp);
                string strMsg = "远程主机：" + socketSend.RemoteEndPoint + "连接成功";
                //使用回调
                ShowLog(strMsg);

                //定义接收客户端消息的线程
                Thread threadReceive = new Thread(new ParameterizedThreadStart(Receive));
                threadReceive.IsBackground = true;
                threadReceive.Start(socketSend);
            }*/
        }

        private void InnerReceive(IAsyncResult iasync)
        {
            try
            {
                Dictionary<string, object> dic = iasync.AsyncState as Dictionary<string, object>;
                Socket temp = dic["Socket"] as Socket;
                byte[] buffer = dic["Buffer"] as byte[];
                //
                //实际接收到的有效字节数
                int count = temp.EndReceive(iasync);
                if (count > 0)
                {
                    var rtype = GetResType2();
                    if (rtype != ResponseType.NoDeal)
                    {
                        byte[] sendData = GetBytesByType(rtype, buffer.Take(count).ToArray());
                        SendLogic(temp, sendData);
                    }
                    //int type = GetResType();
                    //if (type != 0)
                    //{
                    //    byte[] sendData = GetBytesByType(type, buffer.Take(count).ToArray());
                    //    SendLogic(temp, sendData);
                    //}

                    string str = string.Empty;
                    if (radioHexChecked.Checked)
                    {
                        str = BitConverter.ToString(buffer, 0, count);
                    }
                    else
                    {
                        str = Encoding.Default.GetString(buffer, 0, count);
                    }

                    string strReceiveMsg = "接收：" + socketSend.RemoteEndPoint + "发送的消息:" + str;
                    ShowLog(strReceiveMsg);
                }

                buffer = new byte[2048];
                Dictionary<string, object> dic2 = new Dictionary<string, object>();
                dic2.Add("Socket", temp);
                dic2.Add("Buffer", buffer);
                temp.BeginReceive(buffer, 0, 2048, SocketFlags.None, InnerReceive, dic2);
            }
            catch (Exception exc)
            {
                ShowLog(exc.Message);
            }
        }

        string[] colors = new string[] { "红", "黄", "绿", "蓝" };

        private void SendLogic2(Socket socket, byte[] buffer)
        {
            try
            {
                byte[] sendData = new byte[2048];
                //
                byte[] temp1 = new byte[2];
                new Random().NextBytes(temp1);
                byte[] data = new byte[7]{
                    buffer[0],buffer[1],buffer[2],temp1[0],temp1[1],temp1[0],temp1[1]
                };
                byte[] crcs = CRC.CRC16(data);
                sendData = new byte[9] {
                    buffer[0],buffer[1],buffer[2],temp1[0],temp1[1],temp1[0],temp1[1],crcs[0],crcs[1]
                };
                if (BitConverter.IsLittleEndian)
                {
                    sendData[7] = crcs[1];
                    sendData[8] = crcs[0];
                }
                string crcdata = BitConverter.ToString(sendData);
                //
                SocketError socketError;
                socket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, out socketError,
                    new AsyncCallback((iasync) =>
                    {
                        Socket socket1 = iasync.AsyncState as Socket;
                        socket1.EndSend(iasync);
                    }), socket);
            }
            catch (Exception exc)
            {
                ShowLog(exc.Message);
            }
        }

        private byte[] GetBytesByType(ResponseType id, byte[] buffer)
        {
            byte[] sendData = new byte[2];
            if (id == ResponseType.WuXiJianDing)
            {
                string data = Encoding.UTF8.GetString(buffer).TrimEnd(';');
                string[] arrays = data.Split('$');
                if (arrays.Length == 1)
                {
                    return sendData;
                }
                else if (arrays[0].Equals("S1F13"))
                {
                    //上位机连线请求
                    sendData = Encoding.UTF8.GetBytes("S1F14$OK");
                }
                else if (arrays[0].Equals("S1F3"))
                {
                    //上位机设备状态请求
                    sendData = Encoding.UTF8.GetBytes("S1F4$WAITING");
                }
                else if (arrays[0].Equals("S2F13") && arrays.Length == 3 && UtilityHelper.IsValidIP(arrays[1])
                    && arrays[2].Equals("Lamp"))
                {
                    int i = new Random().Next(0, colors.Length);
                    //设置断线重连秒数
                    string comm = "S2F14$" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "$Lamp$" + colors[i];
                    sendData = Encoding.UTF8.GetBytes(comm);
                }
                else if (arrays[0].Equals("S2F48") && arrays.Length == 2)
                {
                    //设置断线重连秒数
                    sendData = Encoding.UTF8.GetBytes("HAS SET CONNETION TIMEOUT TO " + arrays[1]);
                }
                else if (UtilityHelper.IsValidIP(arrays[0]))
                {
                    //第1位是IP地址时
                    if (arrays[1].Equals("S1F13"))
                    {
                        //关联设备连线请求
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F14$OK");
                    }
                    else if (arrays[1].Equals("S1F4"))
                    {
                        //关联设备状态请求
                        //sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F4$");
                    }
                    else if (arrays[1].Equals("S1F15"))
                    {
                        //关联设备短线状态请求
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F16$OK");
                    }
                    else if (arrays[1].Equals("S2F13"))
                    {
                        //
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S2F14$OK");
                    }
                    else if (arrays[1].Equals("S1F3"))
                    {
                        //
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F4$RUNNING");
                    }
                }
            }
            else if (id == ResponseType.TempHumitSensor)
            {
                byte[] temp1 = new byte[2];
                new Random().NextBytes(temp1);
                byte[] data = new byte[7]{
                    buffer[0],buffer[1],buffer[2],temp1[0],temp1[1],temp1[0],temp1[1]
                };
                byte[] crcs = CRC.CRC16(data);
                sendData = new byte[9] {
                    buffer[0],buffer[1],buffer[2],temp1[0],temp1[1],temp1[0],temp1[1],crcs[0],crcs[1]
                };
                if (BitConverter.IsLittleEndian)
                {
                    sendData[7] = crcs[1];
                    sendData[8] = crcs[0];
                }
            }
            else if (id == ResponseType.IOMotor)
            {
                //01 04 00 00 00 20 F1 D2
                if (buffer.Length == 8 && buffer[1] == 0x04 && buffer[2] == 0 && buffer[3] == 0
                    && buffer[4] == 0 && buffer[5] == 0x20)
                {
                    byte[] temp = new byte[]
                    {
                        buffer[0], buffer[1], 0x40,
                        0,0,0,0,0,0,0,0,0,0,
                        0,0,0,0,0,0,0,0,0,0,
                        0,0,0,0,0,0,0,0,0,0,
                        0,0,0,0,0,0,0,0,0,0,
                        0,0,0,0,0,0,0,0,0,0,
                        0,0,0,0,0,0,0,0,0,0,
                        0,0,0,0
                    };
                    byte[] crc = CRC.CRC16(temp);
                    //
                    sendData = new byte[69];
                    Array.Copy(temp, sendData, temp.Length);
                    if (BitConverter.IsLittleEndian)
                    {
                        crc = crc.Reverse().ToArray();
                    }
                    Array.Copy(crc, 0, sendData, 67, crc.Length);
                }
            }
            else if (id == ResponseType.AutoMaster)
            {
                byte startOfText = 0x02;
                byte endOfText = 0x03;
                if (buffer[0] == startOfText && buffer[buffer.Length - 1] == endOfText)
                {
                    string command = Encoding.ASCII.GetString(buffer, 1, buffer.Length - 2);
                    Newtonsoft.Json.Linq.JObject jobj = Newtonsoft.Json.Linq.JObject.Parse(command);
                    var cmd = jobj.Property("CMD");
                    if (cmd != null && cmd.Value != null)
                    {
                        AutoMasterCommand commd = cmd.Value.ToObject<AutoMasterCommand>();
                        if (commd != null)
                        {
                            JObject jr = new JObject();
                            if (commd == AutoMasterCommand.StartMark || commd == AutoMasterCommand.StopMark)
                            {
                                jr.Add("CMD", new JValue("OK"));
                            }
                            else if (commd == AutoMasterCommand.BoardStatus)
                            {
                                if (DateTime.Now.Second % 2 == 0)
                                {
                                    jr.Add("CMD", new JValue("Busy"));
                                }
                                else
                                {
                                    jr.Add("CMD", new JValue("Idle"));
                                }
                            }
                            //
                            if (jr.HasValues)
                            {
                                var arr = Encoding.UTF8.GetBytes(jr.ToString());
                                sendData = new byte[arr.Length + 2];
                                Array.Copy(arr, 0, sendData, 1, arr.Length);
                                sendData[0] = 0x02;
                                sendData[arr.Length - 1] = 0x03;
                            }
                        }
                    }
                }
            }
            return sendData;
        }

        private void SendLogic(Socket socket, byte[] buffer)
        {
            try
            {
                SocketError socketError;
                socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, out socketError,
                    new AsyncCallback((iasync) =>
                    {
                        Socket socket1 = iasync.AsyncState as Socket;
                        socket1.EndSend(iasync);
                    }), socket);
            }
            catch (Exception exc)
            {
                ShowLog(exc.Message);
            }
        }

        private void SendLogic1(Socket socket, byte[] buffer)
        {
            try
            {
                byte[] sendData = new byte[2048];
                //
                //46-49-4E-53-00-00-00-0C-00-00-00-00-00-00-00-00-00-00-00-64
                byte[] omulong = new byte[] {
0x46,0x49,0x4E,0x53,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64
                };
                //
                string data = Encoding.UTF8.GetString(buffer).TrimEnd(';');
                string[] arrays = data.Split('$');
                if (arrays.Length == 1)
                {
                    return;
                }
                else if (arrays[0].Equals("S1F13"))
                {
                    //上位机连线请求
                    sendData = Encoding.UTF8.GetBytes("S1F14$OK");
                }
                else if (arrays[0].Equals("S1F3"))
                {
                    //上位机设备状态请求
                    sendData = Encoding.UTF8.GetBytes("S1F4$WAITING");
                }
                else if (arrays[0].Equals("S2F13") && arrays.Length == 3 && UtilityHelper.IsValidIP(arrays[1])
                    && arrays[2].Equals("Lamp"))
                {
                    int i = new Random().Next(0, colors.Length);
                    //设置断线重连秒数
                    string comm = "S2F14$" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "$Lamp$" + colors[i];
                    sendData = Encoding.UTF8.GetBytes(comm);
                }
                else if (arrays[0].Equals("S2F48") && arrays.Length == 2)
                {
                    //设置断线重连秒数
                    sendData = Encoding.UTF8.GetBytes("HAS SET CONNETION TIMEOUT TO " + arrays[1]);
                }
                else if (UtilityHelper.IsValidIP(arrays[0]))
                {
                    //第1位是IP地址时
                    if (arrays[1].Equals("S1F13"))
                    {
                        //关联设备连线请求
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F14$OK");
                    }
                    else if (arrays[1].Equals("S1F4"))
                    {
                        //关联设备状态请求
                        //sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F4$");
                    }
                    else if (arrays[1].Equals("S1F15"))
                    {
                        //关联设备短线状态请求
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F16$OK");
                    }
                    else if (arrays[1].Equals("S2F13"))
                    {
                        //
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S2F14$OK");
                    }
                    else if (arrays[1].Equals("S1F3"))
                    {
                        //
                        sendData = Encoding.UTF8.GetBytes(arrays[0] + "$S1F4$RUNNING");
                    }
                }
                else
                {
                    bool match = true;
                    for (int x = 0; x < 10; x++)
                    {
                        if (buffer[x] != omulong[x])
                        {
                            match = false;
                            break;
                        }
                    }
                    if (match)
                    {
                        sendData = buffer;
                    }
                }
                //
                SocketError socketError;
                socket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, out socketError,
                    new AsyncCallback((iasync) =>
                    {
                        Socket socket1 = iasync.AsyncState as Socket;
                        socket1.EndSend(iasync);
                    }), socket);
            }
            catch (Exception exc)
            {
                ShowLog(exc.Message);
            }
        }

        /// <summary>
        /// 服务器端不停的接收客户端发送的消息
        /// </summary>
        /// <param name="obj"></param>
        private void Receive(object obj)
        {
            try
            {
                Socket socketSend = obj as Socket;
                //客户端连接成功后，服务器接收客户端发送的消息
                byte[] buffer = new byte[2048];
                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("Socket", socketSend);
                dic.Add("Buffer", buffer);
                socketSend.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(InnerReceive), dic);
            }
            catch (Exception exc)
            {
                ShowLog(exc.Message);
            }
            /*while (true)
            {
                //客户端连接成功后，服务器接收客户端发送的消息
                byte[] buffer = new byte[2048];
                //实际接收到的有效字节数
                int count = socketSend.Receive(buffer);
                if (count == 0)//count 表示客户端关闭，要退出循环
                {
                    break;
                }
                else
                {
                    string str = BitConverter.ToString(buffer, 0, count); // Encoding.Default.Getstring(buffer, 0, count);
                    string strReceiveMsg = "接收：" + socketSend.RemoteEndPoint + "发送的消息:" + str;
                    ShowLog(strReceiveMsg);
                }
            }*/
        }

        /// <summary>
        /// 回调委托需要执行的方法
        /// </summary>
        /// <param name="strValue"></param>
        private void SetTextValue(string strValue)
        {
            this.txt_Log.AppendText(strValue + Environment.NewLine);
        }

        Action<string> setCallBack = null;
        private void ShowLog(string strValue)
        {
            if (setCallBack == null)
            {
                setCallBack = new Action<string>(SetTextValue);
            }
            txt_Log.Invoke(setCallBack, strValue);
        }

        private void ReceiveMsg(string strMsg)
        {
            //this.txt_Log.AppendText(strMsg + Environment.NewLine);
            ShowLog(strMsg);
        }

        private void AddCmbItem(string strItem)
        {
            if (!this.cmb_Socket.Items.Contains(strItem))
            {
                this.cmb_Socket.Items.Add(strItem);
            }
        }

        /// <summary>
        /// 服务器给客户端发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Send_Click(object sender, EventArgs e)
        {
            try
            {
                string strMsg = this.txt_Msg.Text.Trim();
                byte[] buffer;
                if (radioStrChecked.Checked)
                {
                    buffer = Encoding.Default.GetBytes(strMsg);
                }
                else
                {
                    buffer = CRC.StringToHexByte(strMsg);
                }
                //List<byte> list = new List<byte>();
                //list.Add(0);
                //list.AddRange(buffer);
                ////将泛型集合转换为数组
                //byte[] newBuffer = list.ToArray();
                //获得用户选择的IP地址
                string ip = this.cmb_Socket.SelectedItem.ToString();
                //(System.Net.IPAddress.HostToNetworkOrder()
                int len = dicSocket[ip].Send(buffer);
                ReceiveMsg($"已发出{len}个byte:{BitConverter.ToString(buffer)}");
            }
            catch (Exception ex)
            {
                MessageBox.Show("给客户端发送消息出错:" + ex.Message);
            }
            //socketSend.Send(buffer);
        }

        /// <summary>
        /// 选择要发送的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Select_Click(object sender, EventArgs e)
        {
            OpenFileDialog dia = new OpenFileDialog();
            //设置初始目录
            dia.InitialDirectory = @"";
            dia.Title = "请选择要发送的文件";
            //过滤文件类型
            dia.Filter = "所有文件|*.*";
            dia.ShowDialog();
            //将选择的文件的全路径赋值给文本框
            this.txt_FilePath.Text = dia.FileName;
        }

        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendFile_Click(object sender, EventArgs e)
        {
            List<byte> list = new List<byte>();
            //获取要发送的文件的路径
            string strPath = this.txt_FilePath.Text.Trim();
            using (FileStream sw = new FileStream(strPath, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[2048];
                int r = sw.Read(buffer, 0, buffer.Length);
                list.Add(1);
                list.AddRange(buffer);

                byte[] newBuffer = list.ToArray();
                //发送
                //dicSocket[cmb_Socket.SelectedItem.ToString()].Send(newBuffer, 0, r+1, SocketFlags.None);
                btn_SendFile.Invoke(sendCallBack, newBuffer);
            }

        }

        private void SendFile(byte[] sendBuffer)
        {
            try
            {
                dicSocket[cmb_Socket.SelectedItem.ToString()].Send(sendBuffer, SocketFlags.None);
            }
            catch (Exception ex)
            {
                MessageBox.Show("发送文件出错:" + ex.Message);
            }
        }

        private void btn_Shock_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1] { 2 };
            dicSocket[cmb_Socket.SelectedItem.ToString()].Send(buffer);
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_StopListen_Click(object sender, EventArgs e)
        {
            if (socketWatch != null)
                socketWatch.Close();
            if (socketSend != null)
                socketSend.Close();
            //终止线程
            if (AcceptSocketThread != null)
                AcceptSocketThread.Abort();
            if (threadReceive != null)
                threadReceive.Abort();
        }

        private void FrmServer_Load(object sender, EventArgs e)
        {
            DataTable respTable = new DataTable();
            respTable.Columns.Add("id", typeof(int));
            respTable.Columns.Add("name", typeof(string));
            //
            var r = Enum.GetNames(typeof(ResponseType));
            foreach (object obj in Enum.GetValues(typeof(ResponseType)))
            {
                int id = Convert.ToInt32(obj);
                respTable.Rows.Add(id, Enum.GetName(typeof(ResponseType), id));
            }
            //
            comboBox1.DataSource = respTable;
            comboBox1.ValueMember = respTable.Columns[0].ColumnName;
            comboBox1.DisplayMember = respTable.Columns[1].ColumnName;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.SelectedIndex = 0;
        }

        enum ResponseType {
            /// <summary>
            /// 不做处理
            /// </summary>
            NoDeal = 0,
            /// <summary>
            /// 无锡健鼎EEP
            /// </summary>
            WuXiJianDing = 1,
            /// <summary>
            /// 温湿度传感器
            /// </summary>
            TempHumitSensor = 2,
            /// <summary>
            /// 32路IO模块
            /// </summary>
            IOMotor = 3,
            /// <summary>
            /// 镭射条码打印
            /// </summary>
            AutoMaster = 4,
        };

        Func<int> handlerResType = null;
        Func<ResponseType> handlerResType2 = null;

        private int GetResType()
        {
            if (handlerResType == null)
            {
                handlerResType = new Func<int>(() => {
                    int i = Convert.ToInt32(comboBox1.SelectedValue.ToString());
                    return i;
                });

            }
            object obj = comboBox1.Invoke(handlerResType);
            return Convert.ToInt32(obj.ToString());
        }

        private ResponseType GetResType2()
        {
            if (handlerResType2 == null)
            {
                handlerResType2 = new Func<ResponseType>(() =>
                {
                    var x = Enum.Parse(typeof(ResponseType), comboBox1.SelectedValue.ToString());
                    return (ResponseType)x;
                });
            }
            object obj = comboBox1.Invoke(handlerResType2);
            return (ResponseType)obj;
        }

        enum AutoMasterCommand {
            /// <summary>
            /// 命令开始打标
            /// </summary>
            StartMark,
            /// <summary>
            /// 停止打标
            /// </summary>
            StopMark,
            /// <summary>
            /// 获取板卡状态
            /// </summary>
            BoardStatus,
        };

        enum AutoMasterResponse
        {
            /// <summary>
            /// StartMark,StopMark应答
            /// </summary>
            OK,
            /// <summary>
            /// 初始化或打标中
            /// </summary>
            Busy,
            /// <summary>
            /// 空闲状态
            /// </summary>
            Idle
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetResType2();

            Newtonsoft.Json.Linq.JObject jobj = new Newtonsoft.Json.Linq.JObject();

        }

    }

}